<?php

namespace App\Admin\Controllers;

use App\Models\Withdraw;
use App\Models\Wallet;
use App\Models\User;
use App\Models\PowerLog;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use App\Admin\Extensions\Failed;
use App\Admin\Extensions\Success;
use App\Events\SendNoticeToOne;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class WithdrawController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('提现管理')
            ->description('提现管理')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('Detail')
            ->description('description')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('Edit')
            ->description('description')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('Create')
            ->description('description')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Withdraw);

        $grid->model()->where('status',0)->orderBy('id','desc');
        $grid->id('Id');
        $grid->user()->phone('手机号');
        $grid->partner_trade_no('商家流水号');
        $grid->channel('提现渠道')->display(function($value){
            switch($value)
            {
                case '1':
                    return '余额提现';
                    break;
                case '2':
                    return '收益提现';
                case '3':
                    return '退还押金';
                    break;
                default:
                    break;
            }
        });
        $grid->money('提现金额');
        $grid->type('提现类型')->display(function($value){
            switch($value)
            {
                case '1':
                    return '微信';
                    break;
                case '2':
                    return '支付宝';
                    break;
                case '3':
                    return '银行卡';
                    break;
                default:
                    break;
            }
        });
        $grid->status('状态')->display(function($value){
            switch($value)
            {
                case '0':
                    return "<span class='label label-warning'>待审核</span>";
                    break;
                case '1':
                    return "<span class='label label-success'>已通过</span>";
                    break;
                case '2':
                    return "<span class='label label-primary'>已取消</span>";
                    break;
                case '3':
                    return "<span class='label label-danger'>未通过</span>";
                    break;
                default:
                    break;
            }
        });
        $grid->comment('备注');
        $grid->created_at('申请时间');

        $grid->actions(function ($actions) {
            $actions->disableDelete();
            $actions->disableEdit();
            $actions->disableView();            
            $row = $actions->row;
             // 添加操作
            $actions->append(new Success($actions->getKey()));
            $actions->append(new Failed($actions->getKey()));
                    
        });

        $grid->filter(function ($filter) {
            // 去掉默认的id过滤器
            $filter->disableIdFilter();
            $filter->equal('type', '提现至')->radio([
                1 => '微信',
                2 => '支付宝',
                3 => '银行卡',
            ]);
            $filter->equal('status', '状态')->radio([
                0 => '待审核',
                1 => '已通过',
                2 => '已取消',
                3 => '未通过',
            ]);
            $filter->scope('支付宝')->where('type', 1);
            $filter->scope('今日新增', '今日新增')->whereDate('created_at', date('Y-m-d'));

        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Withdraw::findOrFail($id));

        $show->id('Id');
        $show->user_id('User id');
        $show->out_no('Out no');
        $show->money('Money');
        $show->type('Type');
        $show->status('Status');
        $show->comment('Comment');
        $show->created_at('Created at');
        $show->updated_at('Updated at');

        return $show;
    }



    //审核通过
    public function success(Request $request, Wallet $wallet)
    {
        $id = $request->id;
        $withdraw = Withdraw::findOrFail($id);
        $wallet = Wallet::where('user_id',$withdraw->user_id)->first();
        $user = User::where('id',$withdraw->user_id)->first();
        if($withdraw->money > $wallet->money){
            return $this->ajax_error('该用户余额不足');
        }
        switch ($withdraw->channel) {
            case '1':
                if($withdraw->speed == 1){
                    $amount = bcmul($withdraw->money, 0.95, 2)*100;
                }else{
                    $amount = bcmul($withdraw->money, 0.97, 2)*100;
                }
                break;
            case '2':
                if($withdraw->speed == 1){
                    $amount = bcmul($withdraw->money, 0.95, 2)*100;
                }else{
                    $amount = bcmul($withdraw->money, 0.97, 2)*100;
                }
            case '3':
                $amount = $withdraw->money;//退还押金
                if ($withdraw->money > $wallet->deposit) {
                    return $this->ajax_error('押金余额不足');
                }
                $wallet->deposit = bcsub($wallet->deposit, $withdraw->money, 2);
                $wallet->money = bcadd($wallet->money,$withdraw->money,2);
                $user->is_member = 0;
                $user->level = 0;
                $user->member_start_time = 0;
                $user->member_end_time = 0;
                $user->fid = 0;
                $user->shop_id = 0;
                $withdraw->status = 1;
                $withdraw->save();
                $wallet->save();
                $user->save();
                event(new SendNoticeToOne($user,2,9));
                return $this->ajax_success('操作成功');

            default:
                
                break;
        }
        // $amount = ($withdraw->money)*100;
        
        $order = [
            'partner_trade_no' => $withdraw->partner_trade_no,          
            'openid' => $user->weixin_withdraw_openid,                 
            'check_name' => 'FORCE_CHECK',            
            're_user_name'=>$user->real_name,             
            'amount' => $amount,                      
            'type' => 'app',
            'desc' => 'E衣余额提现',  
        ];
        try{
            $res = app('wechat_pay')->transfer($order);
        } catch (\Exception $e) {
            return $this->ajax_error(($e->raw)['err_code_des']);                      
        }


        
        $withdraw->status = 1;
        $withdraw->payment_no = $res->payment_no;
        $withdraw->pay_at = $res->payment_time;

        switch ($withdraw->channel) {
            case '1'://钱包提现
                $wallet->money = bcsub($wallet->money, $withdraw->money, 2);
                $wallet->computing_power = bcsub($wallet->computing_power, 20, 2);
                break;
            case '2':
                $wallet->shop_money = bcsub($wallet->shop_money, $withdraw->money, 2);
                $wallet->computing_power = bcsub($wallet->computing_power, 20, 2);
            case '3':
                // if ($withdraw->money > $wallet->deposit) {
                //     return $this->ajax_error('押金余额不足');
                // }
                // $wallet->deposit = bcsub($wallet->deposit, $withdraw->money, 2);
                // $user->is_member = 0;
                // $user->level = 0;
                // $user->member_start_time = 0;
                // $user->member_end_time = 0;
                // $user->fid = 0;
                // $user->shop_id = 0;
            default:               
                break;
        }


        DB::beginTransaction();
        try {
            $withdraw->save();
            $wallet->save();
            $user->save();
            if($withdraw->channel !==3){
                PowerLog::add_log($withdraw->user_id, 6, 20, 2);
            }
            DB::commit();

            return $this->ajax_success('操作成功');

        } catch (\Exception $exception) {

            DB::rollBack();

            return $this->ajax_error('操作失败');

        }

    }
    //审核不通过
    public function failed(Request $request)
    {
        $id = $request->id;
        $recharge = Recharge::findOrFail($id);
        $recharge->status = 3;
        $recharge->comment = $request->comment;
        $res = $recharge->save();
        if ($res) {
            return $this->ajax_success('操作成功');
        } else {
            return $this->ajax_error('操作失败');
        }

    }


}
